package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.graphics.Color;
import android.os.Bundle;
import android.view.View;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.CollectionUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.stark.apkextract.lib.model.AeExporter;
import com.stark.apkextract.lib.model.AeUtil;

import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.AppAdapter;
import flc.ast.bean.ApkBean;
import flc.ast.bean.MyDocBean;
import flc.ast.databinding.ActivityApkManagerBinding;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.base.GeneralEvtDialog;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.StkPermissionHelper;

public class ApkManagerActivity extends BaseAc<ActivityApkManagerBinding> {

    private AppAdapter appAdapter;
    private boolean isEdit = false;
    private List<ApkBean> listSel = new ArrayList<>();


    @Override
    protected int onCreate() {
        return R.layout.activity_apk_manager;
    }

    @Override
    protected void initView() {
        mDataBinding.ivApkManageBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mDataBinding.rvApkList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        appAdapter = new AppAdapter();
        mDataBinding.rvApkList.setAdapter(appAdapter);
        appAdapter.setOnItemClickListener(this);

        mDataBinding.ivApkRecord.setOnClickListener(this);
        mDataBinding.ivApkManage.setOnClickListener(this);
        mDataBinding.ivManageCancel.setOnClickListener(this);
        mDataBinding.ivManageExport.setOnClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivApkManage:
                listSel.clear();
                isEdit = true;
                appAdapter.setEdit(isEdit);
                for (ApkBean validDatum : appAdapter.getValidData()) {
                    validDatum.setSelected(false);
                }
                appAdapter.notifyDataSetChanged();
                mDataBinding.ivApkRecord.setVisibility(View.GONE);
                mDataBinding.ivApkManage.setVisibility(View.GONE);
                mDataBinding.llManage.setVisibility(View.VISIBLE);
                break;
            case R.id.ivManageCancel://取消
                isEdit = false;
                appAdapter.setEdit(isEdit);
                appAdapter.notifyDataSetChanged();
                mDataBinding.ivApkRecord.setVisibility(View.VISIBLE);
                mDataBinding.ivApkManage.setVisibility(View.VISIBLE);
                mDataBinding.llManage.setVisibility(View.GONE);
                break;
            case R.id.ivManageExport://导出
                if (listSel.size() != 1) {
                    ToastUtils.showShort(getString(R.string.please_sel_one));
                    return;
                }
                getPermission();
                isEdit = false;
                appAdapter.setEdit(isEdit);
                appAdapter.notifyDataSetChanged();
                mDataBinding.ivApkRecord.setVisibility(View.VISIBLE);
                mDataBinding.ivApkManage.setVisibility(View.VISIBLE);
                mDataBinding.llManage.setVisibility(View.GONE);
                break;
            case R.id.ivApkRecord://导出记录
                startActivity(ExportRecordActivity.class);
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (isEdit) {
            if (appAdapter.getItem(position).isSelected()) {
                appAdapter.getItem(position).setSelected(false);
                listSel.remove(appAdapter.getItem(position));
                appAdapter.notifyDataSetChanged();
            } else {
                listSel.add(appAdapter.getItem(position));
                appAdapter.getItem(position).setSelected(true);
                appAdapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    protected void initData() {
        loadApks();
    }

    private void loadApks() {
        showDialog(getString(com.stark.common.res.R.string.loading));
        RxUtil.create(new RxUtil.Callback<List<String>>() {
            @Override
            public void doBackground(ObservableEmitter<List<String>> emitter) {
                emitter.onNext(AeUtil.getNoSystemInstalledPackageNames());
            }

            @Override
            public void accept(List<String> packageNames) {
                if (!CollectionUtils.isEmpty(packageNames)) {
                    mDataBinding.rvApkList.setVisibility(View.VISIBLE);
                    mDataBinding.ivApkManageNoData.setVisibility(View.GONE);
                    List<ApkBean> apkBeans = new ArrayList<>();
                    ApkBean bean;
                    for (String packageName : packageNames) {
                        bean = new ApkBean();
                        bean.pkgName = packageName;
                        apkBeans.add(bean);
                    }
                    appAdapter.setList(apkBeans);
                } else {
                    mDataBinding.rvApkList.setVisibility(View.GONE);
                    mDataBinding.ivApkManageNoData.setVisibility(View.VISIBLE);
                }
                dismissDialog(500L);
            }
        });
    }

    //获取权限
    private void getPermission() {
        StkPermissionHelper.reqManageExternalStoragePermission()
                .reqPermissionDesc(getString(R.string.get_app_permission))
                .callback(new StkPermissionHelper.ACallback() {
                    @Override
                    public void onGranted() {
                        exportAfter();
                    }
                })
                .request();
    }

    private void exportAfter() {
        for (ApkBean apkBean : listSel) {
            String packageName = listSel.get(0).pkgName;
            AeExporter.getInstance().export(packageName);
            boolean isExist = AeExporter.getInstance().isExportExist(packageName);
            if (isExist) {
                //已存在
                String apkFileName = AeExporter.getExportFileName(packageName);
                String exportRootDir = AeExporter.getExportRootDir();
                String content = getString(R.string.ae_apk_exist_tip_fmt, apkFileName, exportRootDir);
                new GeneralEvtDialog.Builder(this)
                        .title(getString(com.stark.common.res.R.string.prompt))
                        .content(content)
                        .leftBtnText(getString(com.stark.common.res.R.string.cover))
                        .leftBtnListener(v -> {
                            startExport(packageName);
                        })
                        .rightBtnText(getString(com.stark.common.res.R.string.no_cover))
                        .rightBtnTextColor(Color.parseColor("#0000FF"))
                        .build()
                        .show();
                return;
            }

            //不存在
            String appName = AppUtils.getAppName(packageName);
            String exportRootDir = AeExporter.getExportRootDir();
            String content = getString(R.string.ae_apk_not_exist_tip_fmt, appName, exportRootDir);
            new GeneralEvtDialog.Builder(this)
                    .title(getString(com.stark.common.res.R.string.prompt))
                    .content(content)
                    .rightBtnListener(v -> {
                        startExport(packageName);
                    })
                    .rightBtnTextColor(Color.parseColor("#0000FF"))
                    .build()
                    .show();
        }
    }

    private void startExport(String packageName) {
        showDialog(getString(com.stark.common.res.R.string.exporting));
        RxUtil.create(new RxUtil.Callback<Boolean>() {
            @Override
            public void doBackground(ObservableEmitter<Boolean> emitter) {
                emitter.onNext(AeExporter.getInstance().export(packageName));
            }

            @Override
            public void accept(Boolean success) {
                dismissDialog();
                if (success != null && success) {
                    ToastUtils.showShort(getString(com.stark.common.res.R.string.export_success));
                } else {
                    ToastUtils.showShort(getString(com.stark.common.res.R.string.export_failure));
                }
            }
        });
    }

}